package cn.momoshenchi.handler;

import cn.momoshenchi.ResultInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/5/15 - 14:00
 */
@Configuration
public class MyFailureHandler  implements AuthenticationFailureHandler
{
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException
    {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        ResultInfo resultInfo=new ResultInfo(401,"登陆失败");
        if(e instanceof BadCredentialsException)
        {
            resultInfo.setMsg("账号密码错误");
        }
        ObjectMapper objectMapper=new ObjectMapper();
        String s = objectMapper.writeValueAsString(resultInfo);

        writer.write(s);
        writer.flush();
        writer.close();
    }
}
